import os
import csv
import time
import struct
import pymysql

data_folder = 'D:/Data/'  # 保存CSV文件的文件夹
save_interval = 60  # 每300秒保存一个新的CSV文件
db_phy = {
    'host': '118.190.236.225',  # 主机
    'user': 'root',  # 用户名
    'password': '123456',  # 密码
    'port': 8306,  # 端口
    'database': 'cw'  # 数据库名
}

# 从usb读取数据
def read_from_usb():
    # 连接phy库
    connection_phy = pymysql.connect(**db_phy)
    # 创建游标对象
    cursor_phy = connection_phy.cursor()

    try:
        while True:
            buffer = "11111"
            # 获取当前时间戳
            timestamp = time.strftime("%Y-%m-%d %H:%M:%S")

            # 插入数据库
            insert_query = "INSERT INTO base (startdate, content_data) VALUES (%s, %s)"
            rows = (timestamp, buffer)
            cursor_phy.execute(insert_query, rows)

            # 提交事务
            connection_phy.commit()  # 确保在 Connection 对象上调用 commit()

            time.sleep(1)

    except (pymysql.Error) as error:
        print(error)


if __name__ == "__main__":
    read_from_usb()